<?php
/**
 * Created by PhpStorm.
 * User: zhou
 * Date: 2019/3/15
 * Time: 下午5:20
 */

namespace App\Library;

use Illuminate\Database\Query\Builder;

/**
 *  order[0][column]: 3
    * order[0][dir]: asc
    * start: 0
    * length: 10
 * Class Datatable
 * @package App\Library
 */
class Datatable
{
    public static $total; //总记录数。

    /**对查询构建起封装成可以识别datable.js插件在server processing模式下的数据来返回数据的方法
     * @param array $postdata   前端传过来的数据
     * @param $builder          查询构建起  Eloquent或Builder
     * @return mixed            返回builder
     */
    public static function packQuery(array $postdata,$builder)
    {
        //搜索
        $searchable_arr = self::filter_by_value($postdata['columns'],'searchable','true');
        $field_name_arr = array_column($searchable_arr,'data');
        if(empty(!$postdata['search']['value'])) {
            $builder->Where(function ($query) use ($field_name_arr, $postdata) {
                foreach ($field_name_arr as $filed) {
                    if ($filed == 'function') {
                        continue;
                    }
                    $query->orwhere($filed, 'like', '%' . $postdata['search']['value'] . '%');
                }
            });
        }
        //排序
        $order_column = $postdata['order']['0']['column'];//那一列排序，从0开始
        $order_dir = $postdata['order']['0']['dir'];//ase desc 升序或者降序
        if(isset($postdata['columns'][$order_column]) && !empty($postdata['columns'][$order_column]['data']) && $postdata['columns'][$order_column]['data']!='function' ){
            $builder -> orderBy($postdata['columns'][$order_column]['data'],$order_dir);
        }

        self::$total = (clone $builder) -> count();

        //分页
        $builder -> offset($postdata['start'])
                 -> limit($postdata['length']);

        return $builder;
    }

    /**返回databale.js可以识别的数据结果。
     * @param $postdata
     * @param array $result
     * @return array
     */
    public static function packResult($postdata,array $result)
    {
       return [
           'draw' => intval($postdata['draw']),
           'recordsTotal' => intval(self::$total),
           'recordsFiltered' => intval(self::$total),
           'data' => $result
       ];
    }


    private static function filter_by_value ($array, $index, $value){
        if(is_array($array) && count($array)>0)
        {
            foreach(array_keys($array) as $key){
                $temp[$key] = $array[$key][$index];

                if ($temp[$key] == $value){
                    $newarray[$key] = $array[$key];
                }
            }
        }
        return $newarray;
    }



}